package com.lib.common.dialog_fragment;

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

import com.lib.common.R;

import java.lang.ref.WeakReference;
import java.text.MessageFormat;

/**
 * @author FengLing
 * 描述：
 * Created on 2019-03-27 10:11:53
 */
class VCodeHandler extends Handler {
    static final int MSG_SHOW_WAIT = 1;
    static final int MSG_SEND_ERR = 2;

    private static final int DEFAULT_WAIT_TIME = 60;
    private int sRemainTime = DEFAULT_WAIT_TIME;

    private String mGetCode;
    private BaseDialogFragment mFragment;
    private TextView mSendVerifyCode;

    VCodeHandler(BaseDialogFragment fragment, TextView sendVerifyCode) {
        if (mFragment == null) {
            return;
        }
        mGetCode = mFragment.getString(R.string.get_v_code);
        mFragment = new WeakReference<>(fragment).get();
        mSendVerifyCode = new WeakReference<>(sendVerifyCode).get();
    }

    @Override
    public void handleMessage(Message msg) {
        if (mFragment == null) {
            return;
        }
        switch (msg.what) {
            case MSG_SHOW_WAIT: {
                mSendVerifyCode.setText(MessageFormat.format("{0}s", --sRemainTime));
                if (sRemainTime <= 0) {
                    mSendVerifyCode.setText(mGetCode);
                    mSendVerifyCode.setEnabled(true);
                    sRemainTime = DEFAULT_WAIT_TIME;
                } else {
                    sendEmptyMessageDelayed(MSG_SHOW_WAIT, 1000);
                }
            }
            break;
            case MSG_SEND_ERR:
                mSendVerifyCode.setEnabled(true);
                Toast.makeText(mFragment.getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
        }
    }

    public void onDestroy() {

    }
}